package fulbitofacil.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import fulbitofacil.exception.DAOExcepcion;
import fulbitofacil.modelo.ReservaCancha;
import fulbitofacil.util.ConexionBD;

public class ReservaCanchaDAO extends BaseDAO {
	
	public Collection<ReservaCancha> ListarCancha(String distrito, Date fecIni, Date fecFin, int horIni, int horFin) throws DAOExcepcion {
		System.out.println("Reserva: ListarCancha(String nombre)");
		String query = "SELECT di.nombre as distrito, can.nombre, can.idCanchaFul as idCancha, " +
				"lo.Persona_idPersona as idPersona, hor.idHoraAtencion, hor.fecha, hor.hora, hor.estado, " +
				"alq.HoraAtencion_idHoraAtencion as hora_alq FROM Local as lo INNER JOIN distrito as di ON lo.Distrito_idDistrito=Di.idDistrito " +
				"INNER JOIN Canchaful as can ON lo.idLocal = can.Local_IdLocal INNER JOIN " +
				"(SELECT dias.* , horas.* FROM diasatencion as dias INNER JOIN horaatencion as horas ON dias.idDiasAtencion = horas.DiasAtencion_idDiasAtencion)" +
				" as hor ON hor.CanchaFul_idCanchaFul = can.idCanchaFul " +
				"LEFT JOIN Alquiler as alq ON Hor.idHoraAtencion = Alq.HoraAtencion_idHoraAtencion WHERE alq.HoraAtencion_idHoraAtencion is null " +
				//" AND hor.fecha <>? AND hor.fecha <>? AND hor.hora >=? AND hor.hora <= ? AND di.nombre<>?";
		        " AND hor.hora >=? AND hor.hora <= ? AND hor.fecha >= ? AND hor.fecha <= ? AND di.nombre=?";
		
		Collection<ReservaCancha> Lista = new ArrayList<ReservaCancha>();
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);			
			
			stmt.setInt(1, horIni);
			stmt.setInt(2, horFin);
			stmt.setDate(3, fecIni);
			stmt.setDate(4, fecFin);
			stmt.setString(5, distrito);
			
			rs = stmt.executeQuery();
			
			while (rs.next()) {
				ReservaCancha vo = new ReservaCancha();				
				vo.setDistrito(rs.getString("distrito"));
				vo.setNombre(rs.getString("nombre"));
				vo.setIdCancha(rs.getInt("idCancha"));
				vo.setIdPersona(rs.getInt("idPersona"));
				vo.setIdHoraAtencion(rs.getInt("idHoraAtencion"));
				vo.setFecha(rs.getDate("fecha"));
				vo.setHora(rs.getInt("hora"));				
				Lista.add(vo);
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return Lista;
	}
	

}
